<template>
  <div>
    <el-dialog
      v-bind="$attrs"
      title="外部资源引用"
      width="600px"
      :close-on-click-modal="false"
      @open="onOpen"
      @close="onClose"
    >
      <el-input
        v-for="(item, index) in resources"
        :key="index"
        v-model="resources[index]"
        class="url-item"
        placeholder="请输入 css 或 js 资源路径"
        prefix-icon="el-icon-link"
        clearable
      >
        <template #append>
          <el-button icon="el-icon-delete" @click="deleteOne(index)" />
        </template>
      </el-input>
      <el-button-group class="add-item">
        <el-button
          plain
          @click="addOne('https://lib.baomitu.com/jquery/1.8.3/jquery.min.js')"
        >
          jQuery1.8.3
        </el-button>
        <el-button plain @click="addOne('https://unpkg.com/http-vue-loader')">
          http-vue-loader
        </el-button>
        <el-button icon="el-icon-circle-plus-outline" plain @click="addOne('')">
          添加其他
        </el-button>
      </el-button-group>
      <template #footer>
        <div>
          <el-button @click="close"> 取消 </el-button>
          <el-button type="primary" @click="handelConfirm"> 确定 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import { ref, watch, onMounted } from "vue";
import { deepClone } from "../utils/common";

const props = defineProps({
  originResource: Array,
});

const resources = ref(null);

const emit = defineEmits(["update:visible", "save"]);

const onOpen = () => {
  resources.value = props.originResource.length
    ? deepClone(props.originResource)
    : [""];
};

const close = () => {
  emit("update:visible", false);
};

const handleConfirm = () => {
  const results = resources.value.filter((item) => !!item) || [];
  emit("save", results);
  close();
  if (results.length) {
    resources.value = results;
  }
};

const deleteOne = (index) => {
  resources.value.splice(index, 1);
};

const addOne = (url) => {
  if (resources.value.indexOf(url) > -1) {
    ElMessageBox.message("资源已存在");
  } else {
    resources.value.push(url);
  }
};

const onClose = () => {
  resources.value = null;
};
</script>

<style lang="scss" scoped>
.add-item {
  margin-top: 8px;
}
.url-item {
  margin-bottom: 12px;
}
</style>
